
package com.lichuandi.util;

import java.util.concurrent.*;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Supplier;

public class CompletableFutureUtils {

    /**
     * 带异常处理的supplyAsync
     */
    public static <T> CompletableFuture<T> supplyAsyncWithException(
            Supplier<T> supplier,
            Function<Throwable, T> exceptionHandler) {
        return CompletableFuture.supplyAsync(supplier)
                .exceptionally(exceptionHandler);
    }

    /**
     * 带超时的get方法
     */
    public static <T> T getWithTimeout(
            CompletableFuture<T> future,
            long timeout,
            TimeUnit unit) throws ExecutionException, InterruptedException, TimeoutException {
        return future.get(timeout, unit);
    }

    /**
     * 并行执行多个任务
     */
    @SafeVarargs
    public static <T> CompletableFuture<Void> runInParallel(CompletableFuture<T>... futures) {
        return CompletableFuture.allOf(futures);
    }

    /**
     * 结果转换处理
     */
    public static <T, R> CompletableFuture<R> thenTransform(
            CompletableFuture<T> future,
            Function<T, R> transformer) {
        return future.thenApply(transformer);
    }

    /**
     * 组合两个任务的结果
     */
    public static <T, U, R> CompletableFuture<R> combineResults(
            CompletableFuture<T> future1,
            CompletableFuture<U> future2,
            BiFunction<T, U, R> combiner) {
        return future1.thenCombine(future2, combiner);
    }
}
